<template>
  <div class="releaseContainer flex-row autoGrow">
    <choose-service-account
      :multiple="true"
      :showList="false"
      @serviceChange="serviceChange"
      :defalutcheckedWxid="services.map(item=>item.id)"
    >
      <div class="subTitle">已执行自动踢人账号</div>
      <div class="description">默认只对是群主的群生效</div>
      <ul class="scrollAuto autoGrow releaseServiceAccounts">

        <ul class="scrollAuto autoGrow checkList">
          <li :class="['serviceItem', 'listItem', 'flex-row']" v-for="(item) in services" :key="item.id">
            <label class="list-label flex-row">
              <div class="flex-row autoGrow">
              <div class="list-item-avatar">
                <img :src="item.src||item.avatar||defaultAvatar" alt="">
              </div>
              <div class="service-item-info list-item-info flex-column">
                <div class="serviceItemTopInfo listItemTopInfo flex-row">
                    <div class="serviceItemName listItemName textEllipsis">{{item.nick}}</div>
                </div>
                <div class="serviceItemBottomInfo list-item-bottom-info flex-row">
                  <span v-if="item.friendcount||item.friendcount==0">好友{{item.friendcount}}</span>
                  <span v-if="item.groupCount||item.groupCount==0">群{{item.groupCount}}</span>
                </div>
              </div>
              </div>
              <div class="deleteBox flex-column">
                <i class="layui-icon layui-icon-close" @click="deleteService(item)"></i>
              </div>
            </label>
          </li>
        </ul>

      </ul>
    </choose-service-account>
    <div class="settingOptions">
      <div class="flex-row adHeader">
        <div class="subTitle">防广告</div>
        <span class="clickedSpan" @click="showWhiteList">白名单</span>
      </div>
      <div class="settingOption">
        <input type="checkbox" :checked="settings.includes('message')" value="message" @change="adSetting"><span>踢消息中包括关键词</span><span class="clickedSpan"  @click="openAdDialog">设置</span>
      </div>
      <div class="settingOption"><input type="checkbox" :checked="settings.includes('nickname')" value="nickname" @change="adSetting"><span>踢昵称中包括关键词</span><span class="clickedSpan" @click="openAdDialog">设置</span></div>
      <div class="settingOption"><input disabled type="checkbox" :checked="settings.includes('qrcode')" value="qrcode" @change="adSetting"><span>踢发二维码（暂未实现）</span></div>
      <div class="settingOption"><input type="checkbox" :checked="settings.includes('card')" value="card" @change="adSetting"><span>踢发名片</span></div>
      <div class="settingOption"><input type="checkbox" :checked="settings.includes('file')" value="file" @change="adSetting"><span>踢发文件</span></div>
      <div class="settingOption"><input type="checkbox" :checked="settings.includes('video')" value="video" @change="adSetting"><span>踢发小视频</span></div>
      <div class="settingOption"><input type="checkbox" :checked="settings.includes('miniprogram')" value="miniprogram" @change="adSetting"><span>踢发小程序</span></div>
      <div class="settingOption"><input type="checkbox" :checked="settings.includes('linkshare')" value="linkshare" @change="adSetting"><span>踢发链接分享</span></div>
      <div class="subTitle">防骚扰</div>
      <div class="settingOption">
        <input type="checkbox" :checked="maxLineChecked" value="maxLine" @change="adSetting">
        <span>踢信息大于</span><input type="number" class="layui-input" v-model="maxLine"><span>行</span>
      </div>
      <div class="settingOption">
        <input type="checkbox" :checked="maxCountChecked" value="maxCount" @change="adSetting"><span>踢字符大于</span><input type="number" class="layui-input" v-model="maxCount"><span>字</span>
      </div>
      <div class="settingOption settingType">
        <input type="radio" name="type" value="dismiss" :checked="policy=='dismiss'" @change="setType"><span>直接踢人</span>
      </div>
      <div class="settingOption warnTimeOption">
        <input type="radio" name="type" value="warn" :checked="policy=='warn'" @change="setType">
          <span>警告后再次违规踢人&emsp;警告</span>
          <input type="number" class="layui-input warnTimes" v-model="times"><span>次</span>
      </div>
      <div class="settingOption">
         <input type="radio" name="type" value="warnOnly" :checked="policy=='warnOnly'" @change="setType"><span>只警告不踢人</span><span class="clickedSpan" @click="()=>this.showWarnMessageDialog=true">设置警告语</span>
      </div>
      <div class="settingOption newline">
         <div>
            <input type="checkbox" name="notifyAdmin" v-model="notifyAdmin" :checked="notifyAdmin"><span>通知管理员</span>
         </div>
         <div>
         <el-input v-model="adminWxId" placeholder="管理员微信号"></el-input>
         </div>
         <div>
         <el-input v-model="notifyKeywords" type="textarea" placeholder="通知管理员的关键字，以逗号分隔"></el-input>
         </div>
      </div>
      <div class="settingButtons flex-row">
        <button class="layui-btn layui-btn-sm" @click="submitSetting">提交</button>
        <!-- <button class="layui-btn layui-btn-sm layui-btn-primary" @click="clearSetting">清除设置</button> -->
      </div>
    </div>
    <div class="releaseListContainer flex-column autoGrow">
      <div class="subTitle">触发记录</div>
      <div class="tabs">
        <button :class="['layui-btn', 'layui-btn-xs', curTab!='release' && 'layui-btn-primary']" @click="changeTab('release')">已踢用户</button>
        <button :class="['layui-btn', 'layui-btn-xs', curTab!='warn' && 'layui-btn-primary']" @click="changeTab('warn')">已警告用户</button>
      </div>
      <div class="recordList flex-column autoGrow">
        <user-list-item
          v-for="(user, index) in curTab=='release' ? releaseList : warnList"
          :key="index"
          :item="{ avatar:user.groupmemberavatar||defaultAvatar,nick:user.groupmembernick }"
          :showBadge="false"
          :showGender="false"
          :showLastMessage="false"
          currentUserWxid=""
        >
          <template v-slot:bottomInfo>
            <div>
              {{ getActionTypeByRule(user.rulebroken)}}{{ '警告'+ (user.warningcount||0) +'次'+ (curTab=='release'?'后踢出群':'') }}
            </div>
          </template>
          <template v-slot:attachInfo>

            <div class="listItem group flex-row">
              <group
                :avatar="user.groupavatar"
                :name="user.groupname"

              />
            </div>

          </template>
        </user-list-item>
      </div>
    </div>
    <custom-dialog title="防广告设置"
      :showBtn="true"
      @submit="setAdMessage"
      v-if="showAdDialog"
      :closeDialog="()=>this.showAdDialog=false">
      <div class="dialogOptions">
        <slot v-if="editableKeyWords.message">
          <div class="messageOption flex-row" v-for="(val, index) in editableKeyWords.message" :key="index">
            <span class="inlineBlockSpan">消息关键字：</span>
            <input type="text" :value="val" @change="updateMessage('message', index, $event)" class="layui-input">
            <span class="clickedSpan" @click="addMessage('message')" v-if="index==editableKeyWords.message.length-1">添加</span>
          </div>
        </slot>
        <slot v-if="editableKeyWords.nickname">
          <div class="nicknameOption flex-row" v-for="(val, index) in editableKeyWords.nickname" :key="index+10">
            <span class="inlineBlockSpan">群昵称关键字：</span>
            <input type="text" :value="val" class="layui-input" @change="updateMessage('nickname', index, $event)">
            <span class="clickedSpan" @click="addMessage('nickname')" v-if="index==editableKeyWords.nickname.length-1">添加</span>
          </div>
        </slot>
      </div>
    </custom-dialog>
    <custom-dialog title="白名单" v-if="showWhiteListDialog" wrapClass="whiteListDialog" :closeDialog="()=>{showWhiteListDialog=false;userFilter=''}">
      <div class="listTitle">添加白名单:</div>
      <div class="searchContainer flex-row">
        <span>搜索微信名称：</span>
        <input type="text" class="layui-input" placeholder="请输入关键字" v-model="userFilter">
        <span class="clickedSpan">搜索</span>
      </div>
      <div class="userList flex-row">
        <div class="user flex-row" v-for="(user,i) in filteredUserList" :key="i">
          <img :src="user.avatar || user.src || defaultAvatar" alt="">
          <div class="flex-column userName textEllipsis">
            <div class="textEllipsis">{{user.name}}</div>
            <div><span class="clickedSpan" @click="addToWhiteList(user)">添加</span></div>
          </div>
        </div>
      </div>
      <div class="listTitle">白名单账号列表:</div>
      <div class="whiteList flex-row">
        <div class="user flex-row" v-for="(user,i) in whiteList" :key="user.id">
          <img :src="user.avatar || user.src || defaultAvatar" alt="">
          <div class="flex-column userName textEllipsis">
            <div class="textEllipsis">{{user.friendnick}}</div>
            <div><span class="clickedSpan" @click="deleteFromWhiteList(user, i)">删除</span></div>
          </div>
        </div>
      </div>
    </custom-dialog>
    <custom-dialog title="设置警告语"
      @submit="setWarnMessage"
      :showBtn="true" v-if="showWarnMessageDialog"
      :closeDialog="closeWarnDialog">
      <div class="warnMessageTitle">请设置踢人广告语</div>
      <textarea class="warnMessageText" v-model="editableWarnMessage"></textarea>
    </custom-dialog>
  </div>
</template>
<script>
import ChooseServiceAccount from '@/components/chooseServiceAccount'
import UserListItem from '@/components/userListItem';
import ServiceListItem from '@/components/serviceListItem';
import CustomDialog from '@/components/customDialog';
import group from '@/components/group'
import { mapState } from 'vuex';
import pinyin from '@/lib/pinyin'

export default {
  name: 'release',
  data() {
    return {
      actionType : {
        nickname:'昵称中包括关键词',
        qrcode:'发二维码',
        card:'发名片',
        file:'发文件',
        video:'发小视频',
        miniprogram:'发小程序',
        linkshare:'发链接分享',
        message:'消息中包括关键词',
        maxLine:'消息行数超高',
        maxCount:'消息字数超长'
      },
      showAdDialog: false,
      showWhiteListDialog: false,
      showWarnMessageDialog: false,
      services: [],
      settings: [],
      keywords: {
        message: [''],
        nickname: ['']
      },
      editableKeyWords: {},
      editableWarnMessage: '',
      maxLine: '',
      maxCount: '',
      maxLineChecked: false,
      maxCountChecked: false,
      times: '',
      warnMessage: '',
      notifyAdmin:false,
      adminWxId:'',
      notifyKeywords:'',
      whiteList: [],
      userList: [],
      policy: 'dismiss',
      userFilter: '',
      curTab: 'release',
      releaseList: [],
      warnList: [],
      wxaccounts:[] // 接口中获取设置的账号列表
    }
  },
  created() {
    if(this.uistate.adminid !== -1){
      this.init()
    }
  },
  mounted () {

  },
  components: {
    ChooseServiceAccount,
    ServiceListItem,
    CustomDialog,
    UserListItem,
    group
  },
  watch:{
    'uistate.adminid':function(val){
      if(val && val!==-1)
        this.init()
    },
    'accountMap':function(val,oldVal){
      if(val){
        this.initServices()
      }
    }
  },
  methods: {
    serviceChange(services) {
      this.services = services
    },
    getActionTypeByRule(str){
      if(!str)return ''
      const rules = str.split(',')
      return  this.actionType[rules[rules.length-1]]+' '
    },
    init() {
      this.initSetting()
      this.initRecords()
      this.initWhiteList()
    },
    initServices(){
      const wxaccounts = this.wxaccounts
      let accounts = []
      Object.values(this.accountMap).forEach(item=>{
        if( wxaccounts.includes(item.wxid) ){
          accounts.push(item)
        }
      })
      this.services = accounts
    },
    initSetting() {
      this.$api.rule.getSetting({
        csId: this.csid,
      }).then(data=>{
        this.wxaccounts = data.wxaccounts.split(',')
        const rules = JSON.parse(data.rulejson)
        this.settings = rules.adSetting
        this.maxLine = rules.maxLine
        this.maxLineChecked = !!rules.maxLine
        this.maxCount = rules.maxCount
        this.maxCountChecked = !!rules.maxCount

        this.keywords = rules.keywords
        console.log(this.keywords)
        this.policy = rules.type
        this.times = rules.warnTimes
        this.editableWarnMessage = this.warnMessage = rules.warnContent

        this.whiteListWxids = rules.whiteList

        this.whiteList = this.whiteListWxids.map(u=>({wxid:u})),
        this.notifyAdmin = data.notifyAdmin
        this.adminWxId = data.adminWxId
        this.notifyKeywords = data.notifyKeywords

        console.log(rules)

        this.initServices()
      }).catch(e=>this.$msg(e))
    },
    initRecords() {
      this.$api.rule.history({
        csId: this.csid,
      }).then(data=>{
        let releaseList = [] , warnList = []
        data.forEach(item=>{
          if(item.type === 0){
            warnList.push(item)
          }else{
            releaseList.push(item)
          }
        })
        this.releaseList = releaseList;
        this.warnList = warnList
      }).catch(e=>this.$msg(e))
    },
    showWhiteList(){
      this.initWhiteList()
      this.showWhiteListDialog = true
    },
    initWhiteList() {
      this.userList = []
      this.whiteList = []
      this.services.forEach(item=>{
        this.$api.friend.list({
          csid: this.csid,
          wxaccount:item.wxid
        }).then(data=>{
          this.userList = this.userList.concat(this.transUserData(data))
          data.forEach(item=>{
            const friend = this.whiteListWxids.includes(item.friendwxid)
            if(friend)this.whiteList.push(item)
          })

          console.log(this.whiteList)
        }).catch(e=>this.$msg(e))
      })

    },
    deleteService(service) {
      console.log(service)
      this.services = this.services.filter(item=>item.id !== service.id)
    },
    adSetting(e) {
      const type = e.target.value

      if(e.target.value === 'maxLine'){
        this.maxLineChecked = e.target.checked
      }else if(e.target.value === 'maxCount'){
        this.maxCountChecked = e.target.checked
      }

      if (e.target.checked) {
        this.settings.push(type)
      } else {
        this.settings = this.settings.filter(s=>s != type)
      }
    },
    setType(e) {
      const type = e.target.value;
      this.policy = type
    },
    setAdMessage() {
      this.$set(this.keywords, 'message', this.editableKeyWords.message.filter(msg=>msg!==''))
      this.$set(this.keywords, 'nickname', this.editableKeyWords.nickname.filter(msg=>msg!==''))
    },
    submitSetting() {
      const wxaccounts = this.services.map(item=>item.wxid).join(',')
      const friends = this.whiteList.map(f=>{
        return f.friendwxid
      });
      let rules = {
        whiteList: friends,
        adSetting: this.settings,
        maxLine: this.maxLine,
        maxCount: this.maxCount,
        keywords: this.keywords,
        type: this.policy,
        warnTimes: this.times || 0,
        warnContent: this.warnMessage || '',
        notifyAdmin: this.notifyAdmin,
        adminWxId: this.adminWxId,
        notifyKeywords : this.notifyKeywords

      }
      if(!this.maxLineChecked || typeof this.maxLine==='boolean' ){
        delete rules.maxLine
      }
      if(!this.maxCountChecked|| typeof this.maxCount==='boolean' ){
        delete rules.maxCount
      }
      if(this.warnMessage.trim()=='' && (this.policy=='warn' || this.policy=='warnOnly')){
        return this.$message({
          message: '警告语不能为空！',
          type: 'error'
        })
      }

      if(this.notifyAdmin && (this.adminWxId.trim()=='' || this.notifyKeywords.trim()=='')){
        return this.$message({
          message: '管理员微信号和关键字不能为空！',
          type: 'error'
        })
      }

      this.$api.rule.insertSetting({
        csid: this.csid,
        wxaccounts,
        rulejson: JSON.stringify(rules)
      }).then(rs=>{
        this.$msg('设置成功')
      }).catch(e=>this.$msg(e))
    },
    clearSetting() {
      this.$set(this.keywords, 'message', [''])
      this.$set(this.keywords, 'nickname', [''])

      this.whiteList = []
      this.settings = []
      this.maxLineChecked = false
      this.maxCountChecked = false
      this.maxLine = ''
      this.maxCount = ''
      this.policy = 0
      this.times = 0
      this.warnMessage = 0
      this.notifyAdmin = false
      this.adminWxId = ''
      this.notifyKeywords = ''
    },
    openAdDialog() {

      // keywords: {
      //   message: [''],
      //           nickname: ['']
      // }
      let keys = JSON.parse(JSON.stringify(this.keywords))
      if(!keys.message.length){
        keys.message = ['']
      }
      if(!keys.nickname.length){
        keys.nickname = ['']
      }
      this.editableKeyWords = {
          message: keys.message,
          nickname: keys.nickname
        }
      this.showAdDialog = true
    },
    addMessage(type) {
      const len = this.editableKeyWords[type].length
      if (len == 10) {
        return this.$msg(`最多添加10个${type=='message' ? '消息' : '群昵称'}关键字`)
      }
      this.editableKeyWords[type].push('')
    },
    updateMessage(type, index, e) {
      const val = e.target.value;
      this.editableKeyWords[type][index] = val.trim();
    },
    setWarnMessage() {
      this.warnMessage = this.editableWarnMessage
    },
    closeWarnDialog() {
      this.showWarnMessageDialog=false;
      //this.editableWarnMessage="";
    },
    deleteFromWhiteList(user, index) {
      this.whiteList.splice(index, 1)
      this.whiteListWxids = this.whiteListWxids.filter(wxid=>wxid !== user.friendwxid)
    },
    addToWhiteList(user) {
      this.whiteListWxids.push(user.friendwxid)
      this.whiteList.push(user)
    },
    changeTab(type) {
      this.curTab = type
    }
  },
  computed: {
    ...mapState(['uistate','accountMap']),
    csid(){
      return this.uistate.adminid
    },
    filteredUserList() {
      const keychars = pinyin.getFullChars(this.userFilter).toLocaleLowerCase()
      if (keychars == '') {
        return this.userList
      } else {
        return this.userList.filter(u=>{
          const chars = pinyin.getFullChars( u.friendnick+''+u.friendwxid ).toLocaleLowerCase()
          return chars.indexOf(keychars)>-1
        })
      }
    }
  },
}
</script>
<style scoped>
.newline{
 flex-direction:column !important;
 align-items:flex-start !important
}

.newline div{
  padding-top: 10px;
}

.list-label{
  align-items: center
}
.listItem.group{
  width: 258px
}
</style>
